<template>
  <div>
    <!-- 添加或修改物资采购申请对话框 -->
    <el-dialog 
      :title="title" 
      :modelValue="visible"
      ref="dialogRef"
      @update:modelValue="emit('update:visible', $event)"
      width="900px" 
      append-to-body
      class="seal-dialog"
      @opened="handleDialogOpen"
    >
      <template #default>
        <div style="padding-right: 24px;">
          <el-form ref="admItemApplyFormRef" :model="form" :rules="rules" label-width="140px" label-position="left" style="padding: 20px 0 20px 24px">
            <el-row :gutter="20">
              <el-col :span="24">
                <el-form-item label="申请人" prop="applyName">
                  <el-input v-model="form.applyName" placeholder="请输入申请人名称" disabled />
                </el-form-item>
              </el-col>
              <el-col :span="24">
                <el-form-item label="申请部门" prop="deptId">
                  <el-tree-select
                    v-model="form.deptId"
                    :data="deptTree"
                    placeholder="请选择申请部门"
                    :props="{ label: 'label', value: 'id', children: 'children' }"
                    check-strictly
                    :editable="false"
                    :default-expand-all="true"
                    style="width: 100%"
                    @visible-change="handleVisibleChange"
                    @change="handleDeptChange"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="24">
                <el-form-item label="项目名称" prop="projectIdArray">
                  <el-select
                    v-model="form.projectIdArray"
                    multiple
                    placeholder="请输入项目名称搜索"
                    clearable
                    filterable
                    remote
                    reserve-keyword
                    :remote-method="searchProjects"
                    :loading="projectLoading"
                    style="width: 100%"
                    @change="handleProjectChange"
                  >
                    <el-option
                      v-for="project in projectList"
                      :key="project.id"
                      :label="`${project.proName} (${project.proNumber || ''})`"
                      :value="String(project.id)"
                    />
                    <template #empty>
                      <div class="text-center p-2">
                        <span v-if="projectLoading">加载中...</span>
                        <span v-else-if="projectSearchKeyword && projectList.length === 0">未找到相关项目</span>
                        <span v-else>请输入项目名称进行搜索</span>
                      </div>
                    </template>
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="24">
                <el-form-item label="申请日期" prop="applyTime">
                  <el-date-picker clearable
                    v-model="form.applyTime"
                    type="date"
                    value-format="YYYY-MM-DD"
                    placeholder="请选择申请时间"
                    :default-value="new Date()"
                    :editable="false"
                    style="width: 100%">
                  </el-date-picker>
                </el-form-item>
              </el-col>
              <el-col :span="24">
                <el-form-item label="类别" prop="type">
                  <el-select v-model="form.type"  :empty-values="[null, undefined]" placeholder="请选择类别" style="width: 100%">
                    <el-option
                      v-for="item in item_apply_type"
                      :key="item.value"
                      :label="item.label"
                      :value="item.value"
                    />
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="24">
                <el-form-item label="物品名称" prop="itemName">
                  <el-input v-model="form.itemName" placeholder="请输入物品名称" />
                </el-form-item>
              </el-col>
              <el-col :span="24">
                <el-form-item label="品牌名称" prop="brandName">
                  <el-input v-model="form.brandName" placeholder="请输入品牌名称" />
                </el-form-item>
              </el-col>
              <el-col :span="24">
                <el-form-item label="规格型号" prop="specificationName">
                  <el-input v-model="form.specificationName" placeholder="请输入规格型号" />
                </el-form-item>
              </el-col>
              <el-col :span="24">
                <el-form-item label="用品说明" prop="describe">
                  <el-input v-model="form.describe" placeholder="请输入用品说明" />
                </el-form-item>
              </el-col>
              <el-col :span="24">
                <el-form-item label="数量" prop="amount">
                  <el-input v-model="form.amount" placeholder="请输入数量" />
                </el-form-item>
              </el-col>
              <el-col :span="24">
                <el-form-item label="单位" prop="unit">
                  <el-input v-model="form.unit" placeholder="请输入单位" />
                </el-form-item>
              </el-col>
              <el-col :span="24">
                <el-form-item label="单价" prop="price">
                  <el-input v-model="form.price" placeholder="请输入单价" />
                </el-form-item>
              </el-col>
              <el-col :span="24">
                <el-form-item label="质量要求" prop="qualityRequirement">
                  <el-input v-model="form.qualityRequirement" placeholder="请输入质量要求" />
                </el-form-item>
              </el-col>
              <el-col :span="24">
                <el-form-item label="到货时间" prop="arrivalTime">
                  <el-date-picker clearable
                    v-model="form.arrivalTime"
                    type="date"
                    value-format="YYYY-MM-DD"
                    placeholder="请选择到货时间"
                    :editable="false"
                    style="width: 100%">
                  </el-date-picker>
                </el-form-item>
              </el-col>
              <el-col :span="24">
                <el-form-item label="备注" prop="remark">
                  <el-input v-model="form.remark" placeholder="请输入备注" type="textarea" :rows="3" />
                </el-form-item>
              </el-col>
            </el-row>
          </el-form>
        </div>
      </template>
      <template #footer>
        <div class="dialog-footer">
          <el-button :loading="buttonLoading" type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 审核流程配置对话框 -->
    <ApprovalFlow v-model:visible="approvalFlowVisible" :business-type="'ADM-ITEM-APPLY-AUDIT'"
      :business-id="auditIdForApproval" :key="auditIdForApproval" title="配置物品申请审核流程" @confirm="handleApprovalConfirm"
      @cancel="handleApprovalCancel" />
  </div>
</template>

<script setup name="AdmItemApply" lang="ts">
import { listAdmItemApply, addAdmItemApply, updateAdmItemApply } from '@/api/general/administration/item/apply';
import { AdmItemApplyVO, AdmItemApplyForm } from '@/api/general/administration/item/apply/types';
import type { DeptTreeNode } from '@/api/general/administration/seal/types';
import { getDeptTree } from '@/api/general/administration/seal';
import type { FormRules, ElDialog  } from 'element-plus';
import { useUserStore } from '@/store/modules/user';
import { resetApprovalStatus } from '@/components/ApprovalFlow/api';
import { pageListForQuery, getProInfo } from '@/api/project/init/proInfo';
import type { ProInfoVO } from '@/api/project/init/proInfo/types';

const { proxy } = getCurrentInstance() as ComponentInternalInstance;

const props = defineProps({
  title: {
    type: String,
    default: ''
  },
  visible: {
    type: Boolean,
    default: false
  }
});

const buttonLoading = ref(false);
const admItemApplyFormRef = ref<ElFormInstance>();
const loading = ref(true);
const admItemApplyList = ref<AdmItemApplyVO[]>([]);
const total = ref(0);
const emit = defineEmits(['update:visible', 'success']);
// 引入数据字典
const { item_apply_type } = toRefs<any>(proxy?.useDict('item_apply_type'));

// 提交审核相关
const approvalFlowVisible = ref(false);
const currentSubmitAuditRow = ref<any>(null);
const auditIdForApproval = ref<string | number | undefined>(undefined);

// 搜索关键词
const projectSearchKeyword = ref('');
const flowSearchKeyword = ref('');
const projectLoading = ref(false);
const projectList = ref<ProInfoVO[]>([]);
// 防抖计时器
let projectSearchTimer: NodeJS.Timeout | null = null;
// 防止并发请求覆盖
let currentRequestId = 0;

// 回显状态，防止重复调用
const backfillDone = ref(false);

// 定义需要触发必填校验的部门名称或 ID
const requiredProjectDepts = ["董办", "综合办", "财务中心","商务中心"];

// 部门树初始化
const deptTree = ref<DeptTreeNode[]>([]);
const deptTreeSelectRef = ref();

// 用户信息
const userStore = useUserStore();

// dialogVisible 监听
const dialogRef = ref<InstanceType<typeof ElDialog > | null>(null);;

// 本地时间格式化函数
const formatLocalDate = (date = new Date()) => {
  const padZero = num => String(num).padStart(2, '0');
  return `${date.getFullYear()}-${padZero(date.getMonth() + 1)}-${padZero(date.getDate())}`;
};

const initFormData: AdmItemApplyForm = {
  id: undefined,
  applyId: userStore.userId,
  applyName: userStore.name,
  deptId: userStore.deptId,
  deptName: userStore.deptName,
  projectIdArray: [] as string[],
  projectId: undefined,
  projectName: undefined,
  applyTime: formatLocalDate(),
  type: undefined,
  itemName: undefined,
  brandName: undefined,
  specificationName: undefined,
  describe: undefined,
  amount: undefined,
  unit: undefined,
  price: undefined,
  qualityRequirement: undefined,
  arrivalTime: undefined,
  status: 0,
  remark: undefined,
}
const form = ref<AdmItemApplyForm>({ ...initFormData });
const rules = reactive<FormRules>({
  // 申请人（必填，2-10个字符）
  applyName: [
    { required: true, message: '请输入申请人姓名', trigger: 'blur' },
  ],
  // 申请部门（必填）
  deptId: [
    { required: true, message: '请选择申请部门', trigger: 'change' }
  ],
  projectIdArray: [
    { required: true, message: '请选择项目', trigger: 'change' }
  ],
  // 日期（必填，需为合法日期）
  date: [
    { 
      required: true, 
      message: '请选择申请日期', 
      trigger: 'change',
      validator: (_, value, callback) => {
        if (!value) callback(new Error('请选择日期'));
        else if (isNaN(new Date(value).getTime())) callback(new Error('日期格式无效'));
        else callback();
      }
    }
  ],
  // 类别（必填，只能是两种选项之一）
  type: [
    { 
      required: true, 
      message: '请选择类别', 
      trigger: 'change',
      validator: (_, value, callback) => {
        const validTypes = ['0', '1'];
        if (!validTypes.includes(value)) {
          callback(new Error(`类别必须是${validTypes.join('或')}`));
        } else {
          callback();
        }
      }
    }
  ],
  // 物品名称（必填，1-50字符）
  itemName: [
    { required: true, message: '请输入物品名称', trigger: 'blur' },
    { min: 1, max: 50, message: '长度在1到50个字符', trigger: 'blur' }
  ],
  // 品牌名称
  brandName: [
    { required: true, message: '请输入品牌名称', trigger: 'blur' },
  ],
  // 规格型号
  specificationName: [
    { required: true, message: '请输入规格型号', trigger: 'blur' },
  ],
  // 用品说明
  describe: [
    { required: true, message: '请输入用品说明', trigger: 'blur' },
  ],
  // 数量（必填，必须为大于0的整数）
  amount: [
  { required: true, message: '请输入数量', trigger: 'blur' },
    { 
      pattern: /^\d+(\.\d+)?$/,
      message: '必须为数字',
      trigger: 'blur'
    }
  ],
  // 单位（必填）
  unit: [
    { required: true, message: '请选择单位', trigger: 'change' }
  ],
  // 单价（必填，必须为数字且大于0）
  price: [
    { required: true, message: '请输入单价', trigger: 'blur' },
    { 
      validator: (_, value, callback) => {
        const num = Number(value);
        if (isNaN(num)) callback(new Error('必须为数字'));
        else if (num <= 0) callback(new Error('必须大于0'));
        else callback();
      },
      trigger: 'blur'
    }
  ],
  // 质量要求
  qualityRequirement: [
    { required: true, message: '请输入质量要求', trigger: 'blur' },
  ],
  // 到货时间（必填，且不能早于申请时间）
  arrivalTime: [
    { required: true, message: '请选择到货时间', trigger: 'change' },
    {
      validator: (_, value, callback) => {
        if (!value) return callback(new Error('请选择日期'));
        const selectedDate = new Date(value);
        const applyDate = new Date(form.value.applyTime);
        applyDate.setHours(0, 0, 0, 0);
        selectedDate.setHours(0, 0, 0, 0);
        if (selectedDate < applyDate) {
          callback(new Error('到货时间不能早于申请时间'));
        } else {
          callback();
        }
      },
      trigger: 'change'
    }
  ]
});

// 对话框打开时滚动到顶部
const handleDialogOpen = async () => {
  await nextTick(); // 确保 DOM 渲染完成
  // 使用 document.querySelector 精准获取 Teleport 后的 el-dialog__body
  const scrollBody = document.querySelector<HTMLElement>('.seal-dialog .el-dialog__body');
  if (scrollBody) {
    scrollBody.scrollTop = 0; // 滚动到顶部
  } else {
    console.warn('未找到 el-dialog__body');
  }
};

/** 查询物资采购申请列表 */
const getList = async () => {
  loading.value = true;
  const res = await listAdmItemApply();
  admItemApplyList.value = res.rows;
  total.value = res.total;
  loading.value = false;
}


/** 取消按钮 */
const cancel = () => {
  reset();
  emit('update:visible', false);
}

/** 表单重置 */
const reset = () => {
  form.value = {...initFormData};
  if (form.value.deptId) {
    handleDeptChange(form.value.deptId);
  }
  admItemApplyFormRef.value?.resetFields();
}

/**
 * 检查是否需要触发 handleDeptChange 或补全项目数据
 * 触发条件：
 *   1. 部门存在
 *   2. 项目为空 → 调用 handleDeptChange
 *   3. 项目不为空 → 调用补全逻辑
 */
async function tryHandleDeptChange() {
  const deptId = form.value.deptId;
  const projectId = form.value.projectId;
  const isProjectEmpty =
    projectId === undefined ||
    projectId === null ||
    projectId === '' ||
    (Array.isArray(projectId) && projectId.length === 0);

  console.log('[tryHandleDeptChange] deptId:', deptId, 'projectId:', projectId, 'isProjectEmpty:', isProjectEmpty);

  if (deptId && isProjectEmpty) {
    console.log('[tryHandleDeptChange] 条件满足 → 触发 handleDeptChange');
    handleDeptChange(deptId);
  } else if (projectId) {
    console.log('[tryHandleDeptChange] 项目已存在 → 开始补全项目信息');
    await backfillProjectList(projectId);
  } else {
    console.log('[tryHandleDeptChange] 条件不满足 → 不执行任何操作');
  }
}

/**
 * 补全项目数据，仅用于已有 projectId 时的回显
 */
async function backfillProjectList(projectId: string | string[]) {
  try {
    backfillDone.value = true; // 防止重复调用
    // 转换成数组（支持字符串或数组）
    const ids = Array.isArray(projectId)
      ? projectId
      : projectId.split(',').map(id => id.trim()).filter(Boolean);

    console.log('[backfillProjectList] 待补全项目 ID 列表:', ids);
    const projectPromises = ids.map(id => getProInfo(Number(id)));
    const projectData = await Promise.all(projectPromises);
    projectData.forEach(res => {
      if (res?.data) {
        projectList.value.push({
          id: res.data.id,
          proName: res.data.proName,
          proNumber: res.data.proNumber,
          contractId: 0,
          contractName: '',
          projectRegion: '',
          proType: '',
          proContent: '',
          proPresidentsId: '',
          proLeadersId: '',
          ownerUnit: '',
          proAmount: null,
          proAmountRemark: '',
          proStatus: '',
          remark: '',
          createTime: '',
          createBy: ''
        });
      }
    });
    // ✅ 更新回显，不触发部门逻辑
    form.value.projectIdArray = ids.map(String);
    console.log('[backfillProjectList] 项目补全完成，projectIdArray:', form.value.projectIdArray);
  } catch (error) {
    console.error('[backfillProjectList] 项目补全失败:', error);
  }
}


/** 提交按钮 */
const submitForm = () => {
  admItemApplyFormRef.value?.validate(async (valid: boolean) => {
    if (!valid) return;
    // 处理项目ID：多选数组转成逗号分隔字符串
    form.value.projectId = form.value.projectIdArray?.join(',') || '';
    buttonLoading.value = true;
    try {
      if (form.value.id) {
        await updateAdmItemApply(form.value);
        // 调用重置审核流程接口
        await resetApprovalStatus('ADM-ITEM-APPLY-AUDIT', Number(form.value.id), '不可审核');
      } else {
        const res = await addAdmItemApply(form.value);
        // 触发审核流程配置对话框
        auditIdForApproval.value = res.data;
        approvalFlowVisible.value = true;
      }
      proxy?.$modal.msgSuccess("操作成功");
      emit('update:visible', false);
      emit('success');
      getList();
    } finally {
      buttonLoading.value = false;
    }
  });
};

// 监听对话框关闭
watch(approvalFlowVisible, async (newVal, oldVal) => {
  if (oldVal && !newVal) {
    // 对话框从显示变成隐藏时刷新列表
    emit('success');
  }
});


// 获取部门树
const fetchDeptTree = async () => {
  try {
    const res = await getDeptTree();
    const processNode = (node: any) => {
      if (node.children && node.children.length > 0) {
        // 有子节点 → 禁用，但允许展开
        node.disabled = true;
        node.children.forEach(processNode); // 递归处理子节点
      } else {
        // 叶子节点 → 可选
        node.disabled = false;
      }
    };
    if (Array.isArray(res.data)) {
      res.data.forEach(processNode);
    }
    deptTree.value = res.data;
  } catch (error) {
    console.error('获取部门树失败:', error);
    proxy?.$modal.msgError('获取部门树失败');
  }
};

// 下拉框打开时展开全部节点
const handleVisibleChange = (visible: boolean) => {
  if (visible) {
    // 展开全部节点（treeSelect 内部的 tree 是 el-tree 实例）
    setTimeout(() => {
      const tree = deptTreeSelectRef.value?.$refs?.tree;
       tree?.expandAll?.();
    }, 0);
  }
};

// 日期date转换string方法
function formatDate(str?: string | Date) {
  if (!str) return undefined;
  const date = typeof str === 'string' ? new Date(str) : str;
  const y = date.getFullYear();
  const m = (date.getMonth() + 1).toString().padStart(2, '0');
  const d = date.getDate().toString().padStart(2, '0');
  return `${y}-${m}-${d}`;
}

/** 打开弹窗回显方法 */
const openDialog = async (data?: AdmItemApplyForm) => {
  if (data) {
    Object.assign(form.value, {
      ...data,
      type: data.type !== undefined ? String(data.type) : undefined,
      applyTime: formatDate(data.applyTime),
      arrivalTime: formatDate(data.arrivalTime)
    });
    tryHandleDeptChange();
    // 初始化本地匹配和回显
    if (form.value.projectIdArray?.length) {
      backfillDone.value = false;
      getProjectList(''); // 触发本地匹配 + 远程补全逻辑
    }
  } else {
    await reset();
  }
};

/** 审核流程确认回调 */
const handleApprovalConfirm = async () => {
  try {
    ElMessage.success('工作日志审核流程提交成功');
    approvalFlowVisible.value = false;
    currentSubmitAuditRow.value = null;
    auditIdForApproval.value = undefined;
  } catch (error) {
    console.error('审核流程提交失败:', error);
    ElMessage.error('审核流程提交失败');
  }
};

/** 审核流程取消回调 */
const handleApprovalCancel = () => {
  approvalFlowVisible.value = false;
  currentSubmitAuditRow.value = null;
  auditIdForApproval.value = undefined;
  // 审核流程取消时，表单已经在submitCurrentWorklogs中重置了，这里不需要重复重置
};

// 部门选择处理（安全版）
const handleDeptChange = (selectedId: string | number) => {
  console.log('[handleDeptChange] 选中部门 ID:', selectedId);
  const selectedNode = findNodeById(deptTree.value, selectedId);
  if (!selectedNode) return;

  console.log('[handleDeptChange] 选中部门名称:', selectedNode.label);

  if (requiredProjectDepts.includes(selectedNode.label)) {
    console.log('[handleDeptChange] 部门在必填列表，触发项目搜索');
    searchProjects(selectedNode.label, true); // 传 true
  } else {
    console.log('[handleDeptChange] 部门不在必填列表，清空项目选择');
    form.value.projectIdArray = []; // 清空多选回显
    projectList.value = [];         // 可选：清空下拉列表
  }
};

// 遍历树查找节点
function findNodeById(tree: any[], id: string | number): any {
  for (const node of tree) {
    if (node.id === id) return node;
    if (node.children) {
      const found = findNodeById(node.children, id);
      if (found) return found;
    }
  }
  return null;
}

/** 远程搜索项目 */
const searchProjects = (query: string, isDeptTrigger = false) => {
  projectSearchKeyword.value = query;
  if (projectSearchTimer) clearTimeout(projectSearchTimer);

  projectSearchTimer = setTimeout(() => {
    getProjectList(query || '', isDeptTrigger);
  }, 300);
};

// 获取项目列表
const getProjectList = async (searchKeyword = '', isDeptTrigger = false) => {
  try {
    projectLoading.value = true;
    const requestId = ++currentRequestId;

    const res = await pageListForQuery({
      pageNum: 1,
      pageSize: 50,
      flowStatus: '3',
      proName: searchKeyword || undefined
    });

    if (requestId !== currentRequestId) return; // 避免旧请求覆盖

    projectList.value = res.rows || [];
    console.log('[getProjectList] 接口返回项目列表数量:', projectList.value.length);

    if (isDeptTrigger) {
      // 部门触发搜索 → 全部项目 ID 回显
      form.value.projectIdArray = projectList.value.map(p => String(p.id));
      console.log('[回显] 部门触发 projectIdArray:', form.value.projectIdArray);
    } else if (!backfillDone.value && form.value.projectIdArray?.length) {
      // 回显逻辑：检查本地是否匹配全部 ID
      const missingIds = form.value.projectIdArray.filter(
        id => !projectList.value.some(p => String(p.id) === id)
      );

      if (missingIds.length > 0) {
        console.log('[getProjectList] 有缺失项目，需要调用搜索补全:', missingIds);
        backfillDone.value = true; // 标记已经补全，避免循环

        // 调用远程接口补全
        const projectPromises = missingIds.map(id => getProInfo(Number(id)));
        const projectData = await Promise.all(projectPromises);

        // 将补全的数据加入项目列表并更新回显
        projectData.forEach(res => {
          if (res?.data) {
            projectList.value.push({
              id: res.data.id,
              proName: res.data.proName,
              proNumber: res.data.proNumber,
              contractId: 0,
              contractName: '',
              projectRegion: '',
              proType: '',
              proContent: '',
              proPresidentsId: '',
              proLeadersId: '',
              ownerUnit: '',
              proAmount:  null,
              proAmountRemark: '',
              proStatus: '',
              remark: '',
              createTime: '',
              createBy: ''
            });
          }
        });

        // 确保回显
        form.value.projectIdArray = [...form.value.projectIdArray];
        console.log('[getProjectList] 补全完成，停止回显循环');
      } else {
        console.log('[getProjectList] 本地列表匹配到全部 projectId，回显完成');
        backfillDone.value = true;
      }
    }
  } catch (error) {
    console.error('获取项目列表失败:', error);
    ElMessage.error('获取项目列表失败');
  } finally {
    projectLoading.value = false;
  }
};


/** 处理项目选择变化 */
const handleProjectChange = (value: number | string | undefined) => {
  flowSearchKeyword.value = ''; // 清空流程搜索关键词

  // 项目改变时不清空工作日志列表，允许多个项目的数据共存
};

// 暴露方法给父组件
defineExpose({
  reset,
  openDialog
});

onMounted(() => {
  fetchDeptTree();
});
</script>
<style scoped>
.seal-dialog :deep(.el-dialog__header) {
  text-align: center;
}

/* 合同对话框中的用户选择器样式 */
.user-selector-container {
  width: 100%;
}

.user-selector-container .selected-users {
  display: flex;
  flex-wrap: wrap;
  gap: 4px;
  margin-bottom: 8px;
  min-height: 20px;
}

/* 对话框样式优化 */
:deep(.el-dialog__body) {
  max-height: 70vh;
  overflow-y: auto !important;
  display: block; /* 确保是块级元素 */
}
</style>